package com.mars.diancan.handler;

import com.mars.diancan.VO.ResultVO;
import com.mars.diancan.config.ProjectUrlConfig;
import com.mars.diancan.exception.DiancanAuthorizeException;
import com.mars.diancan.exception.DiancanException;
import com.mars.diancan.utils.ResultVOUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * 全局异常捕获
 * @author MARS
 * @date 2018/7/11
 */
@ControllerAdvice
public class SellerExceptionHandler {
    @Autowired
    private ProjectUrlConfig projectUrlConfig;

    /**
     * 捕获授权拦截登录异常:
     * 1.方法前添加@ExceptionHandler(value=异常类.class)
     */
    @ExceptionHandler(value = DiancanAuthorizeException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public ModelAndView handlerAuthorizeException(){
        return new ModelAndView("redirect:"
                .concat(projectUrlConfig.getWechatOpenAuthorize()) // 授权地址
                .concat("/sell/wechat/qrAuthorize")
                .concat("?returnUrl=")
                .concat(projectUrlConfig.getSell())
                .concat("/sell/seller/login"));
    }

    /**
     * 捕获DiancanException的异常
     */
    @ExceptionHandler(value = DiancanException.class)
    @ResponseBody
    public ResultVO handlerDiancanException(DiancanException e) {
        return ResultVOUtil.error(e.getCode(),e.getMessage());
    }
}
